package io.gitee.bowen_lee.rpc;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;

import io.gitee.bowen_lee.rpc.MyRPCTest.MyContent;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 1. 解析服务端发来的 数据
 * 2. 确定数据消费方(哪个线程)
 * 
 * @author Bowen
 * @since 2022-01-18 16:56:27
 */
public class ClientResponses extends ChannelInboundHandlerAdapter {

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // super.channelRead(ctx, msg);
    ByteBuf buf = (ByteBuf) msg;

    // 1. 判断 长度是否是大于等于 头部长度.是的话.是正确的 包数据
    // 2. 否则不是啊
    if (buf.readableBytes() >= BowenHeader.getHeadLen()) {
      // 读取头部字节
      byte[] bytes = new byte[160];
      buf.readBytes(bytes);
      ByteArrayInputStream in = new ByteArrayInputStream(bytes);
      ObjectInputStream oin = new ObjectInputStream(in);
      BowenHeader header = (BowenHeader) oin.readObject();
      System.out.println(header);
      // TODO 根据id 寻找指定回调
      // https://ke.qq.com/webcourse/3201549/103329230#taid=10621428356405773&vid=5285890812607042570
      // 1:11
      System.out.println(header.requestID);

      // 读取body信息 为什么是 大于等于 ???
      if (buf.readableBytes() >= header.getDataLen()) {
        byte[] bdBytes = new byte[(int) header.getDataLen()];
        buf.readBytes(bdBytes);
        ByteArrayInputStream bdIn = new ByteArrayInputStream(bdBytes);
        ObjectInputStream bdOin = new ObjectInputStream(bdIn);
        MyContent content = (MyContent) bdOin.readObject();
        System.out.println(content);

      }

    }

  }

}
